<template>
	<view class="fix-top-window">
		<view class="uni-header">
			<view class="uni-group hide-on-phone">
				<view class="uni-title">{{$t('codes.text.userManager')}}</view>
				<view class="uni-sub-title"></view>
			</view>
			<view class="uni-group">
				
				<button class="uni-button" type="primary" size="mini"
					@click="addMore">{{$t('common.button.add')}}</button>
				<button class="uni-button" type="warn" size="mini" :disabled="!selectedIndexs.length"
					@click="delTable">{{$t('common.button.batchDelete')}}</button>
				
				<!-- #ifdef H5 -->
				<download-excel class="hide-on-phone" :fields="exportExcel.fields" :data="exportExcelData"
					:type="exportExcel.type" :name="exportExcel.filename">
					<button class="uni-button" type="primary" size="mini">{{$t('common.button.exportExcel')}}</button>
				</download-excel>
				<!-- #endif -->
			</view>
		</view>
		<view class="uni-container">
			<unicloud-db ref="udb" collection="print-users"
				field="_id,type,status,create_date,active_date,device_ip" :where="where"
				page-data="replace" :orderby="orderby" :getcount="true" :page-size="options.pageSize"
				:page-current="options.pageCurrent" v-slot:default="{data,pagination,loading,error,options}"
				:options="options" loadtime="manual" @load="onqueryload">
				<uni-table ref="table" :loading="loading" :emptyText="error.message || $t('common.empty')" border stripe
					type="selection" @selection-change="selectionChange">
					<uni-tr>
            <uni-th align="center" filter-type="search" @filter-change="filterChange($event, '_id')">{{$t('codes.text.code')}}</uni-th>
            
            <uni-th align="center" filter-type="select" :filter-data="options.filterData.types_localdata"
            	@filter-change="filterChange($event, 'type')">{{$t('codes.text.type')}}</uni-th>
            
            <uni-th align="center" filter-type="select" :filter-data="options.filterData.status_localdata"
            	@filter-change="filterChange($event, 'status')">{{$t('codes.text.status')}}</uni-th>
            
            <uni-th align="center" filter-type="timestamp"
            	@filter-change="filterChange($event, 'create_date')" sortable
            	@sort-change="sortChange($event, 'create_date')">{{$t('codes.text.create_date')}}</uni-th>
              
              <uni-th align="center" filter-type="timestamp"
              	@filter-change="filterChange($event, 'active_date')" sortable
              	@sort-change="sortChange($event, 'active_date')">{{$t('codes.text.active_date')}}</uni-th>
            <uni-th align="center">{{$t('codes.text.device_ip')}}</uni-th>

						<uni-th align="center">{{$t('codes.text.operate')}}</uni-th>
					</uni-tr>
					<uni-tr v-for="(item,index) in data" :key="index">
						<uni-td align="center">{{item._id}}</uni-td>
            <uni-td align="center">{{item.type}}</uni-td>
						<uni-td align="center"><text :style="{color:item.status=='已激活'?'#52c41a':''}">{{item.status}}</text> </uni-td>
            
            <uni-td align="center">
            	<uni-dateformat :threshold="[0, 0]" :date="item.create_date"></uni-dateformat>
            </uni-td>
            <uni-td align="center">
            	<uni-dateformat :threshold="[0, 0]" :date="item.active_date"></uni-dateformat>
            </uni-td>
            <uni-td align="center">{{item.device_ip||'-'}}</uni-td>

						<uni-td align="center">
							<view class="uni-group">
								<button @click="confirmDelete(item._id)" class="uni-button" size="mini"
									type="warn">{{$t('common.button.delete')}}</button>
							</view>
						</uni-td>
					</uni-tr>
				</uni-table>
				<view class="uni-pagination-box">
					<!-- #ifndef MP -->
					<picker class="select-picker" mode="selector" :value="pageSizeIndex" :range="pageSizeOption"
						@change="changeSize">
						<button type="default" size="mini" :plain="true">
							<text>{{pageSizeOption[pageSizeIndex]}} {{$t('common.piecePerPage')}}</text>
							<uni-icons class="select-picker-icon" type="arrowdown" size="12" color="#999"></uni-icons>
						</button>
					</picker>
					<!-- #endif -->
					<uni-pagination show-icon :page-size="pagination.size" v-model="pagination.current"
						:total="pagination.count" @change="onPageChanged" />
				</view>
			</unicloud-db>
		</view>
		<!-- #ifndef H5 -->
		<fix-window />
		<!-- #endif -->
    
    <uni-popup ref="popup" type="dialog">
        <uni-popup-dialog mode="base" message="成功消息" :duration="2000" title="新增激活码" :before-close="true" :value="1" @close="close" @confirm="confirm">
          <view class="" style="width: 100%;">
            <view class="" style="font-size:34rpx;color:#666;margin-bottom:12rpx;">
              激活码类型:
            </view>
            <radio-group @change="e=>codeType=e.detail.value" style="display:flex;">
              <label class="" v-for="(item, index) in codeTypes" :key="item.value" style="display: flex;margin-right: 20rpx;">
                <view>
                  <radio :value="item.value" :checked="index === codeType" />
                </view>
                <view>{{item.label}}</view>
              </label>
            </radio-group>
            <view class="" style="font-size:34rpx;color:#666;margin-bottom:12rpx;margin-top:24rpx;">
              激活码数量:
            </view>
            <uni-number-box v-model="codeNum" :min="1" @change="e=>codeNum=e"></uni-number-box>
            
          </view>
          
        </uni-popup-dialog>
    </uni-popup>
	</view>
</template>

<script>
	import {
		enumConverter,
		filterToWhere
	} from '@/js_sdk/validator/uni-id-users.js';
  import moment from 'moment';
  
	const db = uniCloud.database()
	// 表查询配置
	const dbOrderBy = 'create_date desc' // 排序字段
	const dbSearchFields = ['code'] // 支持模糊搜索的字段列表
	// 分页配置
	const pageSize = 20
	const pageCurrent = 1

	const orderByMapping = {
		"ascending": "asc",
		"descending": "desc"
	}

	export default {
		data() {
			return {
				query: '',
				where: '',
				orderby: dbOrderBy,
				orderByFieldName: "",
				selectedIndexs: [],
				pageSizeIndex: 0,
				pageSizeOption: [20, 50, 100, 500],
				tags: {},
				managerTags: [],
				queryTagid: '',
				options: {
					pageSize,
					pageCurrent,
					filterData: {
						"status_localdata": [{
								"text": "未激活",
								"value": 0,
							},
							{
								"text": "已激活",
								"value": 1
							}
						],
            "types_localdata": [{
								"text": "飘带",
								"value": 0
							},
							{
								"text": "卡片",
								"value": 1
							}
						],
					},
					...enumConverter
				},
				imageStyles: {
					width: 64,
					height: 64
				},
				exportExcel: {
					"filename": "codes.xls",
					"type": "xls",
					"fields": {
            "验证码": "_id",
            "验证码类型": "type",
						"验证码状态": "status",
						"创建时间": "create_date",
            "激活时间": "active_date",
            "设备IP": "device_ip"
					}
				},
				exportExcelData: [],
        codeNum: 1,
        codeType: 0,
        codeTypes: [
          {label: '飘带',value:0},
          {label: '卡片',value:1}
        ],
			}
		},
		onLoad(e) {
			this._filter = {}
			const tagid = e.tagid
			if (tagid) {
				this.queryTagid = tagid
				const options = {
					filterType: "select",
					filter: [tagid]
				}
				this.filterChange(options, "tags")
			}

		},
		onReady() {
			if (!this.queryTagid) {
				this.$refs.udb.loadData()
			}
		},
		watch: {
			pageSizeIndex: {
				immediate: true,
				handler(val, old) {
					this.options.pageSize = this.pageSizeOption[val]
					this.options.pageCurrent = 1
					this.$nextTick(() => {
						this.loadData()
					})
				}
			}
		},
    mounted() {
      // this.$request('checkActivate', {
      //   // code: '61cd872207f77200014f18fb'
      //   token: 'JHpb3RBoK37c0oqt3HOJdyJE1J5qsxZuuZJSdfTeZC4vWkkCGTCfVI48Xc+oTmdT'
      // }, {
      //   functionName: 'uni-id-cf',
      //   showModal: false
      // }).then(res=>{
      //   console.log(res);
      // }).catch(err=>{
      //   console.log(err);
      // })
    },
		methods: {
      onqueryload(data) {
      	this.exportExcelData = data.map(item=>{
          item.type = item.type?'卡片':'飘带'
          item.status = this.options.status_valuetotext[item.status]
          if(item.active_date) item.active_date = moment(item.active_date).format('YYYY-MM-DD HH:mm:ss')
          item.create_date = moment(item.create_date).format('YYYY-MM-DD HH:mm:ss')
          return item
        })
      },
			changeSize(e) {
				this.pageSizeIndex = e.detail.value
			},


			getWhere() {
				const query = this.query.trim()
				if (!query) {
					return ''
				}
				const queryRe = new RegExp(query, 'i')
				return dbSearchFields.map(name => queryRe + '.test(' + name + ')').join(' || ')
			},
			
			loadData(clear = true) {
				this.$refs.udb.loadData({
					clear
				})
			},
			onPageChanged(e) {
				this.selectedIndexs.length = 0
				this.$refs.table.clearSelection()
				this.$refs.udb.loadData({
					current: e.current
				})
			},
			navigateTo(url, clear) {
				// clear 表示刷新列表时是否清除页码，true 表示刷新并回到列表第 1 页，默认为 true
				uni.navigateTo({
					url,
					events: {
						refreshData: () => {
							this.loadTags()
							this.loadData(clear)
						}
					}
				})
			},
			// 多选处理
			selectedItems() {
				var dataList = this.$refs.udb.dataList
				return this.selectedIndexs.map(i => dataList[i]._id)
			},
			// 批量删除
			delTable() {
				this.$refs.udb.remove(this.selectedItems(), {
					success: (res) => {
						this.$refs.table.clearSelection()
					}
				})
			},
			// 多选
			selectionChange(e) {
				this.selectedIndexs = e.detail.index
			},
			confirmDelete(id) {
				this.$refs.udb.remove(id, {
					success: (res) => {
						this.$refs.table.clearSelection()
					}
				})
			},
			sortChange(e, name) {
				this.orderByFieldName = name;
				if (e.order) {
					this.orderby = name + ' ' + orderByMapping[e.order]
				} else {
					this.orderby = ''
				}
				this.$refs.table.clearSelection()
				this.$nextTick(() => {
					this.$refs.udb.loadData()
				})
			},
			filterChange(e, name) {
				this._filter[name] = {
					type: e.filterType,
					value: e.filter
				}
				let newWhere = filterToWhere(this._filter, db.command)
				if (Object.keys(newWhere).length) {
					this.where = newWhere
				} else {
					this.where = ''
				}
				this.$nextTick(() => {
					this.$refs.udb.loadData()
				})
			},
      
      // 新增
      addMore(){
        this.$refs.popup.open()
      },
      confirm(e){

        this.$refs.udb.add(Array(parseInt(this.codeNum)).fill({type:this.codeType}), {
          showToast: true,
          success: res=>{
            this.$refs.udb.refresh()
            this.codeType = 0
            this.codeNum = 1
          }
        })
        this.close()
      },
      close(){
        this.$refs.popup.close()
      }
		}
	}
</script>

<style lang="scss">
	.tags-manager {

		&--x {
			width: 400px;
			padding: 40px 30px;
			border-radius: 5px;
			background-color: #fff;
		}

		&--header {
			font-size: 22px;
			color: #333;
			text-align: center;
		}
	}

	.mb {
		margin-bottom: 80px;
	}
	.ml {
		margin-left: 30px;
	}

</style>
